export * from './options'
export const dateRangeSplitToStartAndEnd = (params = {}, argsList = []) => {
  let data = {
    ...params
  }
  for (let i in params) {
    if (argsList.includes(i)) {
      data[`${i}Start`] = params[i][0]
      data[`${i}End`] = params[i][1]
      delete data[i]
    }
  }
  return data
}

export const parseToUrl = (obj) => {
  let s = ''
  for (let i in obj) {
    s += `${i}=${obj[i]}&`
  }
  if (s.length > 2) {
    s.substring(s.length - 2, s.length - 1)
  }
  return s
}

export const urlParamsToObj = (str, bool = false) => {
  let strArr = str.split('&')

  let result = {}

  strArr.forEach((item) => {
    let data = item.split('=')
    let key = bool ? data[0].replace(/([A-Z])/g, '_$1').toLowerCase() : data[0]
    result[key] = data[2]
  })

  return result
}

export const queryKeyToLowerCase = (obj) => {
  let result = {}

  for (let i in obj) {
    result[i.replace(/([A-Z])/g, '_$1').toLowerCase()] = obj[i]
  }

  return result
}

export const flatFlowResult = (list) => {
  list.forEach((row) => {
    if (row.flowResult) {
      row.flowResult = row.flowResult || {}
      Object.assign(row, row.flowResult)
    }
  })

  return list
}

const toString = (val) => Object.prototype.toString.call(val)

export const filterUselessProp = (data, fields = ['rowid', '$cellEdit'], whiteList = []) => {
  let res = {}
  Object.keys(data).forEach((key) => {
    let value = data[key]
    if (whiteList.includes(key)) {
      res[key] = value
      return
    }
    if (Array.isArray(value)) {
      res[key] = value.map((item) => filterUselessProp(item, fields))
    } else if (toString(value) == '[object Object]') {
      res[key] = filterUselessProp(value, fields)
    } else {
      if (fields.includes(key)) {
      } else {
        res[key] = data[key]
      }
    }
  })
  return res
}

export const removeEmpty = (obj) => {
  Object.keys(obj).map((key) => {
    let value = obj[key]
    if (toString(value) == '[object String]' && !obj[key]) {
      delete obj[key]
    }
  })
  return obj
}
// 将obj中为数组的date字段转成字符串
export const objFindDateArray2String = (obj = {}, newLableArr = ['Start', 'End'], labelEnd = 'date') => {
  const res = {}
  Object.keys(obj).forEach((i) => {
    const item = obj[i]
    if (Array.isArray(item) && i.toLowerCase().endsWith(labelEnd)) {
      item.forEach((item2, index2) => {
        if (index2 <= newLableArr.length) {
          res[i + newLableArr[index2]] = item2
        }
      })
    } else {
      res[i] = item
    }
  })
  return res
}

// tree数组转为一维对象
export const treeToOneArr = (arr, props = { label: 'label', value: 'value', children: 'children' }, res = [], func) => {
  let data = JSON.parse(JSON.stringify(arr)) // 对传入的参数进行深拷贝
  let newData = res // 创建空数组用来接收操作后的新数组
  const hasChildren = (item) => {
    // 递归遍历，把包含children的选项拿出来，push到之前新建的空数组内
    ;(item[props.children || 'children'] || (item[props.children || 'children'] = [])).map((v) => {
      hasChildren(v)
    })
    if (!func) {
      newData.push(item)
    } else if (Array.isArray(res)) {
      newData = [...newData, ...func(item)]
    } else {
      newData = { ...newData, ...func(item) }
    }
  }
  data.map((v) => hasChildren(v))
  return newData
}

const lowerField = (prop = '') => prop?.replace(/[A-Z]/, (a) => '_' + a?.toLowerCase())

/**
 * 生成对应数据权限
 * @param {*} option
 * @param {*} fields
 * @param {*} initialOption
 * @returns
 */
export const genFormOptionWithFields = (option, fields = {}, initialOption = {}) => {
  let fieldMap = {
    ...fields
  }

  if (Object.keys(fieldMap).length == 0) return option

  if (initialOption) {
    Object.assign(fieldMap, initialOption)
  }

  const columns = option.column

  columns.forEach((col) => {
    let fieldAuth = fieldMap[col.prop]
    if (fieldAuth == 0) {
      // 可编辑
      col.disabled = false
      col.cell = true
    } else if (fieldAuth == 1) {
      // 只读
      col.disabled = true
    } else if (fieldAuth == 2) {
      // 隐藏
      col.display = false
    }
  })
  return option
}

// 转换驼峰
export const keyToCamel = (key = '') => (key.indexOf('_') > -1 ? key?.replace(/(_[a-z])/g, (s) => s.length === 2 && s.charAt(1).toUpperCase()) : key)

/**
 * 字段权限
 * @param {*} fields
 * @returns
 */
export const authFieldToMap = (fields) => {
  const fieldMap = {}

  if (fields.length > 0) {
    fields.forEach((field) => {
      if (field.name.indexOf('::') > -1) {
        const [key1, key2] = field.name.split('::')
        const camelKey1 = keyToCamel(key1)
        fieldMap[camelKey1] = fieldMap[camelKey1] || {}
        fieldMap[camelKey1][keyToCamel(key2)] = field.type
      } else {
        const key = keyToCamel(field.name)
        fieldMap[key] = field.type
      }
    })
  }

  return {
    ...fieldMap
  }
}

export const genTableOptionWithFields = genFormOptionWithFields

/* 表单验证 报错之后跳转指定位置*/
export const scrollToEl = function (el, result = {}) {
  this.$nextTick(() => {
    const msg = (Object.keys(result)[0] && result[Object.keys(result)[0]][0]?.message) || '请完善需要填写的项'
    this.$message.error(msg)
    const dom = el.$el.querySelector('.is-error')
    dom.scrollIntoView()
    const inputEl = dom.querySelector('input')
    if (inputEl) {
      inputEl.focus()
    } else {
      const textareaEl = dom.querySelector('textarea')
      if (textareaEl) {
        textareaEl.focus()
      }
    }
  })
}

/**
 * 数字格式转换，
 * @param {*} num 数字值
 * @param {*} precision 保留小数后几位，如precision=2，则 1.089 => 1.09
 * @param {*} delEndZero 是否删除末尾无效的0，默认true，如precision=2，如果delEndZero为true 则 1.101 => 1.1 否则 1.101 => 1.10
 * @returns
 */
export function formatNumber(num, precision, delEndZero = true) {
  let numResult
  try {
    if (num) {
      numResult = parseFloat(num)?.toFixed(precision)
      if (delEndZero) {
        numResult = Number(numResult)
      }
    }
  } catch (e) {
    console.error(e)
  }

  return String(numResult || 0)
}

export const filterTime = function (time) {
  var date = new Date(time)

  var h = date.getHours()
  h = h < 10 ? '0' + h : h
  var minute = date.getMinutes()
  minute = minute < 10 ? '0' + minute : minute

  return h + ':' + minute
}
/**
 * 是否是系统定时自动触发的告警模型（非摄像头Ai告警，只有reason字段描述告警信息）
 * @param {*} moduleCode
 * @returns
 */
export const isSysAutoWarnModule = function (moduleCode) {
  // 系统定时自动触发的告警模型列表（非摄像头Ai告警，只有reason字段描述告警信息）
  return ['QYXH', 'WANGDMB', 'QYXS', 'WAGDHLHX', 'YEJSY', 'AISWDK', 'AISWGZ', 'YJSYCZJH', 'JJBWDK', 'JGGWDQ', 'KBGZCZJH'].includes(moduleCode)
}
